package com.zyn.rsgl.controller;


import com.zyn.rsgl.pojo.Approval;
import com.zyn.rsgl.pojo.Leave;
import com.zyn.rsgl.service.LeaveService;
import com.zyn.rsgl.utils.commonResult.R;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 * 请假表 前端控制器
 * </p>
 *
 * @author zcs
 * @since 2025-02-27
 */
@RestController
@RequestMapping("/rsgl/leave")
public class LeaveController {
    @Resource
    private LeaveService leaveService;

    @Resource
    private ApprovalController approvalController;

    // 分页查询
    @GetMapping("/list")
    public R list(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String userId
    ) {
        return leaveService.listPage(pageNum, pageSize, startTime, status, userId);
    }

    // 获取单个请假信息
    @GetMapping("/get/{leaveId}")
    public R get(@PathVariable("leaveId") String leaveId) {
        Leave byId = leaveService.getById(leaveId);
        if (byId != null)
            return R.ok(byId);
        return R.fail("请假信息不存在");
    }

    // 添加请假信息
    @PostMapping("/add")
    public R add(@RequestBody Leave leave) {
        // 判断是否存在
        if (leaveService.getById(leave.getId()) != null)
            return R.fail("请假信息已存在");
        leave.setStatus("待审批");
        boolean isSuccess = leaveService.save(leave);
        if(isSuccess){
            Approval approval = new Approval();
            approval.setOriginalId(leave.getId());
            approval.setUserId(leave.getUserId());
            approval.setType("请假");
            approval.setReason(leave.getReason());
            approval.setStartTime(leave.getStartTime());
            approval.setEndTime(leave.getEndTime());
            approval.setDuration(leave.getDuration());
            approval.setStatus("待审批");
            approvalController.add(approval);
            return R.ok();
        }
        return R.fail("添加失败");
    }

    // 修改请假信息
    @PutMapping("/update")
    public R update(@RequestBody Leave leave) {
        //校验请假天数
        if (leave.getDuration()<1){
            return R.fail("请假天数错误！");
        }
        return leaveService.updateById(leave) ? R.ok() : R.fail("修改失败");
    }

    // 删除请假信息
    @DeleteMapping("/delete/{leaveId}")
    public R delete(@PathVariable("leaveId") String leaveId) {
        return leaveService.removeById(leaveId) ? R.ok() : R.fail("删除失败");
    }
}
